package com.maxdu.labs.stt.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.example.stt.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.models.TPlan;
import com.maxdu.labs.stt.models.TrainingType;
import com.maxdu.labs.stt.models.UserVSTPlan;
import com.maxdu.labs.stt.models.db.TPlanDBHelper;
import com.maxdu.labs.stt.models.db.UserVSTPlanDBHelper;

public class CreateTPlanActivity extends Activity {
	
	private TextView trainingNameResultLabel;
	private TextView trainingNameLabelMandatory;
	private TextView durationLabel;
	private TextView frequencyLabel;
	private TextView frequencyResultLabel;
	private Button typeClimbingBtn;
	private Button typeRunningBtn;
	private Button step1Btn;
	private Button step2Btn;
	private EditText trainingNameText;
	private SeekBar frequencyBar;
	private TextView frequencyResultText1;
	private TextView frequencyResultText2;
	private TextView frequencyResultText3;
	private TextView frequencyResultText4;
	private TextView frequencyResultText5;
	private TextView frequencyResultText6;
	private TextView frequencyResultText7;
	private RadioGroup durationRadioGroup;
	private RadioButton durationOneWeekRadio;
	private RadioButton durationTwoWeekRadio;
	private LinearLayout frequencyLayout;
	private int type;
	private int frequency;
	
	private String currentUser;
	
	private TPlan tplan;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_create_training);
		
	    // Check for an open session
	    final Session session = Session.getActiveSession();
	    if (session != null && session.isOpened()) {
	    	
	        // Get the user's data
	        makeMeRequest(session,false);
	    }
		
		trainingNameResultLabel = (TextView) findViewById(R.id.training_name_result_label);
		trainingNameLabelMandatory = (TextView) findViewById(R.id.training_name_label_mandatory);
		durationLabel = (TextView) findViewById(R.id.duration_label);
		frequencyLabel = (TextView) findViewById(R.id.frequency_label);
		typeClimbingBtn = (Button) findViewById(R.id.type_climbing_btn);
		typeRunningBtn = (Button) findViewById(R.id.type_running_btn);
		step1Btn = (Button) findViewById(R.id.step1_btn);
		trainingNameText = (EditText) findViewById(R.id.training_name_text);
		frequencyResultText1 = (TextView) findViewById(R.id.frequency_result_label_1);
		frequencyResultText2 = (TextView) findViewById(R.id.frequency_result_label_2);
		frequencyResultText3 = (TextView) findViewById(R.id.frequency_result_label_3);
		frequencyResultText4 = (TextView) findViewById(R.id.frequency_result_label_4);
		frequencyResultText5 = (TextView) findViewById(R.id.frequency_result_label_5);
		frequencyResultText6 = (TextView) findViewById(R.id.frequency_result_label_6);
		frequencyResultText7 = (TextView) findViewById(R.id.frequency_result_label_7);
		durationRadioGroup = (RadioGroup) findViewById(R.id.duration_radio_group);
		durationOneWeekRadio = (RadioButton) findViewById(R.id.duration_one_week_radio);
		durationTwoWeekRadio = (RadioButton) findViewById(R.id.duration_two_week_radio);
		
		frequencyBar = (SeekBar) findViewById(R.id.frequency_bar);
		 
		frequencyBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
 
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
				if (progress <= 14){
					frequencyResultText1.setBackgroundColor(Color.BLUE);
					frequencyResultText2.setBackgroundColor(Color.WHITE);
					frequencyResultText3.setBackgroundColor(Color.WHITE);
					frequencyResultText4.setBackgroundColor(Color.WHITE);
					frequencyResultText5.setBackgroundColor(Color.WHITE);
					frequencyResultText6.setBackgroundColor(Color.WHITE);
					frequencyResultText7.setBackgroundColor(Color.WHITE);
				}else if( progress > 14 && progress <= 28){
					frequencyResultText1.setBackgroundColor(Color.WHITE);
					frequencyResultText2.setBackgroundColor(Color.BLUE);
					frequencyResultText3.setBackgroundColor(Color.WHITE);
					frequencyResultText4.setBackgroundColor(Color.WHITE);
					frequencyResultText5.setBackgroundColor(Color.WHITE);
					frequencyResultText6.setBackgroundColor(Color.WHITE);
					frequencyResultText7.setBackgroundColor(Color.WHITE);
				}else if( progress > 28 && progress <= 42){
					frequencyResultText1.setBackgroundColor(Color.WHITE);
					frequencyResultText2.setBackgroundColor(Color.WHITE);
					frequencyResultText3.setBackgroundColor(Color.BLUE);
					frequencyResultText4.setBackgroundColor(Color.WHITE);
					frequencyResultText5.setBackgroundColor(Color.WHITE);
					frequencyResultText6.setBackgroundColor(Color.WHITE);
					frequencyResultText7.setBackgroundColor(Color.WHITE);
				}else if( progress > 42 && progress <= 56){
					frequencyResultText1.setBackgroundColor(Color.WHITE);
					frequencyResultText2.setBackgroundColor(Color.WHITE);
					frequencyResultText3.setBackgroundColor(Color.WHITE);
					frequencyResultText4.setBackgroundColor(Color.BLUE);
					frequencyResultText5.setBackgroundColor(Color.WHITE);
					frequencyResultText6.setBackgroundColor(Color.WHITE);
					frequencyResultText7.setBackgroundColor(Color.WHITE);
				}else if( progress > 56 && progress <= 70){
					frequencyResultText1.setBackgroundColor(Color.WHITE);
					frequencyResultText2.setBackgroundColor(Color.WHITE);
					frequencyResultText3.setBackgroundColor(Color.WHITE);
					frequencyResultText4.setBackgroundColor(Color.WHITE);
					frequencyResultText5.setBackgroundColor(Color.BLUE);
					frequencyResultText6.setBackgroundColor(Color.WHITE);
					frequencyResultText7.setBackgroundColor(Color.WHITE);
				}else if( progress > 70 && progress <= 84){
					frequencyResultText1.setBackgroundColor(Color.WHITE);
					frequencyResultText2.setBackgroundColor(Color.WHITE);
					frequencyResultText3.setBackgroundColor(Color.WHITE);
					frequencyResultText4.setBackgroundColor(Color.WHITE);
					frequencyResultText5.setBackgroundColor(Color.WHITE);
					frequencyResultText6.setBackgroundColor(Color.BLUE);
					frequencyResultText7.setBackgroundColor(Color.WHITE);
				}else{
					frequencyResultText1.setBackgroundColor(Color.WHITE);
					frequencyResultText2.setBackgroundColor(Color.WHITE);
					frequencyResultText3.setBackgroundColor(Color.WHITE);
					frequencyResultText4.setBackgroundColor(Color.WHITE);
					frequencyResultText5.setBackgroundColor(Color.WHITE);
					frequencyResultText6.setBackgroundColor(Color.WHITE);
					frequencyResultText7.setBackgroundColor(Color.BLUE);
				}
			}
 
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}
 
			public void onStopTrackingTouch(SeekBar seekBar) {
				//Toast.makeText(SeekbarActivity.this,"seek bar progress:"+progressChanged, Toast.LENGTH_SHORT).show();
			}
		});
		
		typeClimbingBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				typeClimbingBtn.setBackgroundColor(Color.GREEN);
				typeRunningBtn.setBackgroundColor(Color.GRAY);
				step1Btn.setVisibility(View.VISIBLE);
				type = TrainingType.TYPE_CLIMBING;
			}
		});
		typeRunningBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				typeClimbingBtn.setBackgroundColor(Color.GRAY);
				typeRunningBtn.setBackgroundColor(Color.GREEN);
				step1Btn.setVisibility(View.VISIBLE);
				type = TrainingType.TYPE_RUNNING;
			}
		});
		
		trainingNameText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		    @Override
		    public void onFocusChange(View v, boolean hasFocus) {
		        if (!hasFocus) {
		            hideKeyboard();
		        }
		    }
		});
		
		//step1:
		step1Btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if (trainingNameText.getText().toString().trim().length() > 0){
					trainingNameResultLabel.setText(trainingNameText.getText());
					trainingNameText.setVisibility(View.GONE);
					step1Btn.setVisibility(View.GONE);
					trainingNameLabelMandatory.setVisibility(View.GONE);
					trainingNameResultLabel.setVisibility(View.VISIBLE);
					durationLabel.setVisibility(View.VISIBLE);
					durationRadioGroup.setVisibility(View.VISIBLE);
					durationOneWeekRadio.setVisibility(View.VISIBLE);
					durationTwoWeekRadio.setVisibility(View.VISIBLE);
					frequencyLabel.setVisibility(View.VISIBLE);
					frequencyLayout = (LinearLayout) findViewById(R.id.frequency_layout);
					frequencyLayout.setVisibility(View.VISIBLE);
					
					step2Btn = (Button)findViewById(R.id.step2_btn);
					
					step2Btn.setVisibility(View.VISIBLE);
					
					step2Btn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							frequencyResultLabel = (TextView) findViewById(R.id.frequency_result_label);
							frequency = getFrequencyResult();
							if(frequency == 1){
								frequencyResultLabel.setText(getResources().getString(R.string.one_time_a_week));
							}else{
								frequencyResultLabel.setText(String.format(getResources().getString(R.string.x_times_a_week), frequency));
							}
							frequencyResultLabel.setVisibility(View.VISIBLE);
							frequencyLayout.setVisibility(View.GONE);
							step2Btn.setVisibility(View.GONE);
							
							tplan = new TPlan(null,trainingNameResultLabel.getText().toString(),type,1,frequency);
							//automatically add the current User to this tplan
							if (currentUser != null){
								Log.w(Constants.LOG_TAG,"currentUser is NOT NULL. ===> we can create the UserVSTPlan object");
								UserVSTPlan userVSTPlan = new UserVSTPlan(tplan.getId(),currentUser, -1, UserVSTPlan.INVITATION_ACCEPTED);
								UserVSTPlanDBHelper userVSTPlanDBHelper = new UserVSTPlanDBHelper();
								userVSTPlanDBHelper.saveToCloud(userVSTPlan);
								//create and save to cloud the new tplan
								TPlanDBHelper tplanDBHelper = new TPlanDBHelper();
								tplanDBHelper.saveToCloud(tplan);
							}else{
								Log.w(Constants.LOG_TAG,"currentUser is NULL. Can't create the UserVSTPlan object");
							    if (session != null && session.isOpened()) {
							        // Get the user's data
							        makeMeRequest(session,true);
							    }
							}
							
							Intent intent = new Intent(CreateTPlanActivity.this,SeeTPlanDetailActivity.class);
							intent.putExtra("tplan", tplan);
							intent.putExtra("justCreated", true);
							if (currentUser != null){
								intent.putExtra("currentUser", currentUser);
							}
							startActivity(intent);
							
							Log.w(Constants.LOG_TAG,"++++++++++++++ CreateTrainingActivity ===========> END");
						}
					});
				}else{
					//empty TPlan Name
					trainingNameLabelMandatory.setVisibility(View.VISIBLE);
				}
			}
		});
		
	}

	public void onRadioButtonClicked(View view) {
	    // Is the button now checked?
	    boolean checked = ((RadioButton) view).isChecked();
	    
	    // Check which radio button was clicked
	    switch(view.getId()) {
	        case R.id.duration_one_week_radio:
	            if (checked)
	            break;
	        case R.id.duration_two_week_radio:
	            if (checked)
	            break;
	    }
	}
	private void hideKeyboard(){
		InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
	    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
	}
	
	private int getFrequencyResult(){
		int frequency = frequencyBar.getProgress();
		if (frequency <= 14){
			return 1;
		}else if( frequency > 14 && frequency <= 28){
			return 2;
		}else if( frequency > 28 && frequency <= 42){
			return 3;
		}else if( frequency > 42 && frequency <= 56){
			return 4;
		}else if( frequency > 56 && frequency <= 70){
			return 5;
		}else if( frequency > 70 && frequency <= 84){
			return 6;
		}else if( frequency > 84 && frequency <= 100){
			return 7;
		}else{
			Log.e(Constants.LOG_TAG, "Error: frequency from SeekBar is not betweem 0 and 100. Frequency set to 2 (default value)");
			return 2;
		}
	}
	
	private void makeMeRequest(final Session session, final boolean forceWait) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    currentUser = user.getId();
	                    if(forceWait){
	                    	UserVSTPlan userVSTPlan = new UserVSTPlan(tplan.getId(),currentUser, -1,UserVSTPlan.INVITATION_PENDING);
							UserVSTPlanDBHelper userVSTPlanDBHelper = new UserVSTPlanDBHelper();
							userVSTPlanDBHelper.saveToCloud(userVSTPlan);
							//create and save to cloud the new tplan
							TPlanDBHelper tplanDBHelper = new TPlanDBHelper();
							tplanDBHelper.saveToCloud(tplan);
	                    }
	            	   // GetFriendRequestsTask task = new GetFriendRequestsTask();
	            	   // task.execute(user.getId());
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	} 
}
